<?php
/**
 * Created by PhpStorm.
 * User: saeb
 * Date: 2/11/19
 * Time: 9:03 AM
 */
if (!defined('ABSPATH'))exit('Diee');

if (!function_exists('err_log')) {
    function err_log($obj)
    {
        error_log(
            print_r($obj, true)
        );
    }
}
function gf_ml_get_limits(){
    require_once gf_ml_dir.'includes/gf_ml_wpdb.php';
    $results = gf_ml_get_all_results();
    $result_array = array();
    foreach ($results as $r) {
        $arr = [];
        $arr['id'] = (int) $r['id'];
        $arr['form_id'] = (int) $r['form_id'];
        $arr['limit_number'] = (int) $r['limit_number'];
        $arr['limits_on'] = json_decode($r['limits_on']);
        array_push($result_array,$arr);
    }
    return $result_array;
}
function gf_ml_make_validation_actions($validation_result){
//    err_log($validation_result);
    $form=$validation_result['form'];
    $limits=gf_ml_get_limits();
    foreach ($limits as $l)
    {
        if ($l['form_id'] != $form['id']){
//            err_log($l['form_id']);
//            err_log($form['id']);
            continue;
        }
        else {
            $search_criteria['status'] = 'active';
            foreach ($l['limits_on'] as $fv){
                $online_value=rgpost("input_$fv->field");
//                err_log($fv->value);
                if ($online_value != $fv->value)
                {continue 2;}
                else
                    {
                    $search_criteria['field_filters'][] = array( 'key' => $fv->field, 'value' => $fv->value );
                }
//                err_log($online_value);
            }
            $count_entries = GFAPI::count_entries($form['id'],$search_criteria);
            //err_log($count_entries);
            if ($count_entries>$l['limit_number']){
                $validation_result['is_valid']=false;
                //err_log('should send error');
                $critical_field=array();
                foreach ($l['limits_on'] as $tmpfv){
                    array_push($critical_field,$tmpfv->field);
                }
                foreach ($form['fields'] as $f){
                    if(in_array($f['id'],$critical_field)){
                        //err_log($f);
                        $f->failed_validation=true;
                        $f->validation_message=__p('capacity of your chosed option is full, for more information contact admins');

                    }
                }
            }
//            //err_log($count_entries);
        }
    }

//    err_log($limits[0]);
//    $field=$form['id']['fields'][$fv->value];
//    $field->validation_message=__p('capacity of your chosed option is full, for more information contact admins');
//
//    $validation_result['is_valid']=false;

    return $validation_result;

}



add_filter('gform_validation','gf_ml_make_validation_actions');
